package com.suxin.exception;

import org.springframework.beans.factory.SmartInitializingSingleton;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Tang
 * @classname AbstractExceptionRegister
 * @description [  ]
 * @date 2022/10/12 10:12
 */
public abstract class AbstractExceptionRegister implements SmartInitializingSingleton {

    private static final Map<Class<? extends RuntimeException>, AbstractRuntimeExceptionHandler> runtimeExceptionResposisty = new ConcurrentHashMap<>();

    static {
        runtimeExceptionResposisty.put(RuntimeException.class, new DefaultRuntimeExceptionHandler());
    }

    protected void register() {
        doRegister(runtimeExceptionResposisty);
    }

    protected abstract void doRegister(Map<Class<? extends RuntimeException>, AbstractRuntimeExceptionHandler> runtimeExceptionMap);

    public AbstractRuntimeExceptionHandler getRuntimeExceptionHandler(Throwable throwable) {
        return Optional.ofNullable(runtimeExceptionResposisty.get(throwable.getClass()))
                .orElseGet(() -> {
                    return runtimeExceptionResposisty.get(RuntimeException.class);
                });
    }

    @Override
    public void afterSingletonsInstantiated() {
        register();
    }
}
